package com.hoolai.qps.codes.mina;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.google.protobuf.Message;
import com.google.protobuf.Message.Builder;
import com.hoolai.qps.proto.ReqCmdProto.SaveUserReqCmdProto;

public class ByteBufferCodecFactory implements ProtocolCodecFactory {

	private static Logger logger = Logger.getLogger(ByteBufferCodecFactory.class);

	@Override
	public ProtocolDecoder getDecoder(IoSession session) throws Exception {
		return new ProtocolDecoder() {

			@Override
			public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception {
				// do nothing
			}

			@Override
			public void dispose(IoSession session) throws Exception {
				// do nothing
			}

			@Override
			public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
				// while (in.hasRemaining()) {
				// out.write(in.get());
				// }
				byte[] bytes = new byte[in.limit() - 4];
				logger.info(in.getInt());
				in.get(bytes);
				SaveUserReqCmdProto ping = SaveUserReqCmdProto.parseFrom(bytes);
				out.write(ping);
			}
		};
	}

	@Override
	public ProtocolEncoder getEncoder(IoSession session) throws Exception {
		return new ProtocolEncoder() {

			@Override
			public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
				Builder builder = (Builder) message;
				Message proto = builder.build();
				byte[] bytes = proto.toByteArray();
				IoBuffer buf = IoBuffer.allocate(bytes.length + 4);
				buf.putInt(bytes.length);
				buf.put(bytes);
				buf.flip();
				out.write(buf);
			}

			@Override
			public void dispose(IoSession session) throws Exception {
				// do nothing
			}

		};
	}

}
